#include<iostream>
#include "opencv2/opencv.hpp"
#include "face.h"

using namespace std;
using namespace cv;
using namespace aip;

int main()
{
    VideoCapture cap(0);
    if(!cap.isOpened())
    {
        cout<<"Error opening video stream or file"<<endl;
        return -1;
    }
    cout<<"camera is opened"<<endl;
    
    Mat img;
    Mat greyImg;
    Mat equlizeImg;
    CascadeClassifier classifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml");

    vector<Rect> allFace;//存放人脸的矩形框   
    Mat faceImg;//存放人脸图像
    vector<uchar> jpgBuf;//存放编码后的图像
    
    std::string app_id = "42093362";
    std::string api_key = "jRIa0S9W25h6ykFEngTWTsMz";
    std::string secret_key = "H5NPTRFGu5vy6MqB6KgqEdc4ER2NcLBt";
    aip::Face client(app_id, api_key, secret_key);
    std::string base64Imag;
    Json::Value result;
    Json::Value options;
    options["match_threshold"] = 80;
    time_t sec;

    for(;;)
    {
       cap>>img;
       cvtColor(img,greyImg,CV_BGR2GRAY);//转换为灰度图像
       equalizeHist(greyImg,equlizeImg);//直方图均衡化
       classifier.detectMultiScale(equlizeImg,allFace);//检测人脸 
  
       if(allFace.size())
       {
           for(int i=0;i<allFace.size();i++)
           {
		rectangle(equlizeImg,allFace[i],Scalar(255,255,255),2);//画出人脸矩形框
               faceImg=equlizeImg(allFace[i]);//截取人脸图像
               imencode(".jpg",faceImg,jpgBuf);//编码为jpg格式
	       base64Imag=base64_encode((char *)jpgBuf.data(),jpgBuf.size());
		result = client.face_search_v3(base64Imag,"BASE64","stu", options);
		//cout<<result<<endl;
		if(!result["result"].isNull())
		{
			cout<<result["result"]["user_list"][0]["user_id"]<<endl;
			sec=time(NULL);
			cout<<ctime(&sec)<<endl;
			putText(equlizeImg, result["result"]["user_list"][0]["user_id"].asString(), Point(0,50), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255,255,255));
		}
		else
		{
			cout<<""<<endl;
		}
	   }
       
       }
	namedWindow("Video", WINDOW_NORMAL);
	resizeWindow("Video", equlizeImg.cols, equlizeImg.rows);
       imshow("Video",equlizeImg);
       waitKey(40);
    }
    return 0;
}
